package com.acme.bankapp.domain;

import com.acme.bankapp.exceptions.*;

import java.util.ArrayList;
import java.util.List;

public class QueueImpl implements Queue {
	boolean isClosed = false;
	List<Email> mails = new ArrayList<Email>();

	public void addEmail(Email email) throws QueueIsClosedException {
		synchronized (mails) {
			if (!isClosed) {
				mails.add(email);
				mails.notify();
			} else
				throw new QueueIsClosedException();
		}
	}

	public void close() {
		synchronized (mails) {
			mails.notifyAll();
			isClosed = true;
		}
	}

	public Email getEmail() {
		synchronized (mails) {
			while (mails.isEmpty() && !isClosed) {
				try {
					mails.wait(20);
				} catch (InterruptedException e) {
				}
			}
			if (isClosed && mails.isEmpty())
				return null;
			return mails.remove(0);
		}
	}
}